package com.moli.iov.base.remote.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moli.iov.base.enums.YesOrNoEnum;
import com.moli.iov.base.model.TboxUpgradeFileParam;
import com.moli.iov.base.model.dto.req.SoftVersionReqDto;
import com.moli.iov.base.model.dto.req.TboxUpgradeFileReqDto;
import com.moli.iov.base.model.dto.req.UpgradeFileQueryDto;
import com.moli.iov.base.model.dto.res.TboxUpgradeFileResDto;
import com.moli.iov.base.model.dto.res.VehicleBaseTboxResDto;
import com.moli.iov.base.model.po.TboxUpgradeFile;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.model.po.VehicleTbox;
import com.moli.iov.base.remote.ITboxUpgradeFileRemoteService;
import com.moli.iov.base.service.ITboxUpgradeFileService;
import com.moli.iov.base.service.IVehicleBaseService;
import com.moli.iov.base.service.IVehicleTboxService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.ValidationUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * The type Tbox upgrade file remote service.
 *
 * @author wanghualin
 * @date 2019-10-09 15:47:39
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service(group = "${service.group}")
public class ITboxUpgradeFileRemoteServiceImpl implements ITboxUpgradeFileRemoteService {

    @Autowired
    private ITboxUpgradeFileService iTboxUpgradeFileService;
    @Autowired
    private IVehicleTboxService vehicleTboxService;
    @Autowired
    private IVehicleBaseService iVehicleBaseService;

    @Override
    public RestResponse saveUpgradeFile(TboxUpgradeFileReqDto reqDto) {
        log.info("系统设置-升级包管理-添加-入参TboxUpgradeFileReqDto:{}", JsonUtils.toJson(reqDto));
        ValidationUtils.validateBean(reqDto);
        TboxUpgradeFile byId = iTboxUpgradeFileService.getUpgradeFile(reqDto);
        if (byId != null) {
            return RestResponse.failure("已存在");
        }
        TboxUpgradeFile tboxUpgradeFile = new TboxUpgradeFile();
        CommonUtils.copyProperties(reqDto, tboxUpgradeFile);
        Date time = Calendar.getInstance().getTime();
        tboxUpgradeFile.setGmtCreate(new Date());
        tboxUpgradeFile.setCreateUser(reqDto.getSysUserId().toString());
        tboxUpgradeFile.setGmtModified(time);
        tboxUpgradeFile.setModifiedUser(reqDto.getSysUserId().toString());
        RestResponse restResponse = iTboxUpgradeFileService.saveUpgradeFile(tboxUpgradeFile);
        log.info("系统设置-升级包管理-添加-出参RestResponse:{}", JsonUtils.toJson(restResponse));
        return restResponse;
    }

    private Boolean checkUpgradeFileExist(TboxUpgradeFileReqDto reqDto) {
        ValidationUtils.validateBean(reqDto);
        TboxUpgradeFileParam param = new TboxUpgradeFileParam();
        param.queryEqCompanyId(reqDto.getCompanyId());
        param.queryEqSoftwareVersion(reqDto.getSoftwareVersion());
        param.queryEqVehicleBand(reqDto.getVehicleBand());
        param.queryEqVehicleStyle(reqDto.getVehicleStyle());
        param.queryEqVehilceSeries(reqDto.getVehilceSeries());
        param.queryEqTboxModel(reqDto.getTboxModel());
        reqDto.getId();
        QueryWrapper<TboxUpgradeFile> queryWapper = param.get();
        queryWapper.ne("id", reqDto.getId());
        List<TboxUpgradeFile> list = iTboxUpgradeFileService.list(queryWapper);
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }

    @Override
    public RestResponse updateUpgradeFile(TboxUpgradeFileReqDto reqDto) {
        log.info("系统设置-升级包管理-修改-入参TboxUpgradeFileReqDto:{}", JsonUtils.toJson(reqDto));
        ValidationUtils.validateBean(reqDto, TboxUpgradeFileReqDto.Update.class);
        TboxUpgradeFile byId = iTboxUpgradeFileService.getById(reqDto.getId());
        if (byId == null) {
            return RestResponse.failure("修改失败");
        }
        if (!checkUpgradeFileExist(reqDto)) {
            return RestResponse.failure("已存在");
        }
        CommonUtils.copyProperties(reqDto, byId);
        byId.setGmtModified(new Date());
        byId.setModifiedUser(reqDto.getSysUserId().toString());
        RestResponse restResponse = iTboxUpgradeFileService.updateUpgradeFile(byId);
        log.info("系统设置-升级包管理-修改-出参RestResponse:{}", JsonUtils.toJson(restResponse));
        return restResponse;
    }

    @Override
    public RestResponse deleteUpgradeFile(TboxUpgradeFileReqDto reqDto) {
        log.info("系统设置-升级包管理-删除-入参TboxUpgradeFileReqDto:{}" + JsonUtils.toJson(reqDto));
        ValidationUtils.validateBean(reqDto, TboxUpgradeFileReqDto.Delete.class);
        TboxUpgradeFile byId = iTboxUpgradeFileService.getById(reqDto.getId());
        ValidationUtils.validateBean(byId);
        CommonUtils.copyProperties(reqDto, byId);
        byId.setGmtModified(new Date());
        byId.setModifiedUser(reqDto.getSysUserId().toString());
        byId.setIsDelete(YesOrNoEnum.YES.getCode());
        RestResponse restResponse = iTboxUpgradeFileService.deleteUpgradeFile(byId);
        log.info("系统设置-升级包管理-删除-出参RestResponse:{}" + JsonUtils.toJson(restResponse));
        return restResponse;
    }

    @Override
    public RestResponse<PageExtend<TboxUpgradeFileResDto>> listTboxUpgradeFile(UpgradeFileQueryDto reqDto) {
        log.info("系统设置-升级包管理-列表-入参TboxUpgradeFileReqDto:{}" + JsonUtils.toJson(reqDto));
        RestResponse<PageExtend<TboxUpgradeFileResDto>> success = RestResponse.success(iTboxUpgradeFileService.listTboxUpgradeFile(reqDto));
        log.info("系统设置-升级包管理-列表-出参RestResponse<PageExtend<TboxUpgradeFileResDto>>:{}" + JsonUtils.toJson(success));
        return success;
    }

    @Override
    public RestResponse<Map<String, TboxUpgradeFile>> getUpgradeFileByVin(List<String> vinList) {

        Map<String, TboxUpgradeFile> upgradeFileMap = new HashMap<>();
        //查询所有的升级文件信息
        List<TboxUpgradeFile> upgradeFiles = iTboxUpgradeFileService.queryAll();
        if (CollectionUtils.isEmpty(upgradeFiles)) {
            return RestResponse.failure("查询升级文件信息失败");
        }
        List<VehicleTbox> vehicleTboxList = vehicleTboxService
                .listVehicleTboxList(vinList);
        List<VehicleBase> vehicleBases = iVehicleBaseService.lisVehicleBaseByVin(vinList);
        //组装
        List<VehicleBaseTboxResDto> baseTboxResDto = assemblyVehicleBaseTboxResDto(vehicleTboxList,
                vehicleBases);
        for (VehicleBaseTboxResDto tboxResDto : baseTboxResDto) {
            for (TboxUpgradeFile upgradeFile : upgradeFiles) {
                if (equals(tboxResDto, upgradeFile)) {
                    upgradeFileMap.put(tboxResDto.getVin(), upgradeFile);
                    break;
                }
            }
        }
        return RestResponse.success(upgradeFileMap);
    }

    @Override
    public RestResponse<TboxUpgradeFileResDto> getTboxUpgradeFileById(TboxUpgradeFileReqDto reqDto) {
        ValidationUtils.validateBean(reqDto, TboxUpgradeFileReqDto.Details.class);
        TboxUpgradeFile byId = iTboxUpgradeFileService.getById(reqDto.getId());
        TboxUpgradeFileResDto dto = new TboxUpgradeFileResDto();
        CommonUtils.copyProperties(byId, dto);
        return RestResponse.success(dto);
    }

    @Override
    public RestResponse<List<TboxUpgradeFileResDto>> listSoftVersion(SoftVersionReqDto reqDto) {
        List<TboxUpgradeFileResDto> list = iTboxUpgradeFileService.listSoftVersion(reqDto);
        return RestResponse.success(list);
    }

    private List<VehicleBaseTboxResDto> assemblyVehicleBaseTboxResDto(
            List<VehicleTbox> vehicleTboxList, List<VehicleBase> vehicleBases) {
        List<VehicleBaseTboxResDto> resDtoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(vehicleTboxList) && !CollectionUtils.isEmpty(vehicleBases)) {
            for (VehicleTbox tbox : vehicleTboxList) {
                VehicleBaseTboxResDto dto = new VehicleBaseTboxResDto();
                CommonUtils.copyProperties(tbox, dto);
                c:
                for (VehicleBase vehicleBase : vehicleBases) {
                    if (vehicleBase.getVin().equals(dto.getVin())) {
                        CommonUtils.copyProperties(vehicleBase, dto);
                        break c;
                    }
                }
                resDtoList.add(dto);
            }
        }
        return resDtoList;
    }

    boolean equals(VehicleBaseTboxResDto vehicleTbox, TboxUpgradeFile tboxUpgradeFile) {

        if (Objects.equals(vehicleTbox.getBrand(), tboxUpgradeFile.getVehicleBand())//品牌
                && Objects.equals(vehicleTbox.getVehicleType(), tboxUpgradeFile.getVehicleStyle())//车型
                && Objects.equals(vehicleTbox.getVehicleSeries(), tboxUpgradeFile.getVehilceSeries())//款式
                && Objects.equals(vehicleTbox.getSupplierName(), tboxUpgradeFile.getTboxManufacturer())
                //tbox厂家
                && Objects.equals(vehicleTbox.getDeviceModel(), tboxUpgradeFile.getTboxModel())//tbox型号
                // tbox厂家
                && vehicleTbox.getCompanyId().longValue() == tboxUpgradeFile.getCompanyId().longValue()//tbox型号
                && Objects
                .equals(vehicleTbox.getTboxVersion(), tboxUpgradeFile.getTboxVersion())) {//tbox硬件版本号
            return true;
        } else {
            return false;
        }
    }
}
